package com.edu.web.servlet;

import com.alibaba.fastjson2.JSON;
import com.edu.entity.User;
import com.edu.service.UserService;
import com.edu.service.imlp.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取信息
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //查询
        String meg = "失败";
        User byUsernameAndPassword = userService.getByUsernameAndPassword(username, password);
        if (byUsernameAndPassword != null) {
            //登录成功
            req.getSession().setAttribute("user", byUsernameAndPassword);
            req.getSession().setAttribute("id", byUsernameAndPassword.getId());
            meg = "成功";
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("meg", meg);
        map.put("user", byUsernameAndPassword);
        String jsonString = JSON.toJSONString(map);
        PrintWriter writer = resp.getWriter();
        writer.print(jsonString);
        writer.flush();
        writer.close();
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
